<?php
class Blog extends Authenticated_Controller {
 
    public function __construct() 
    { 
        parent::__construct();
 
        $this->load->model('post_model');
        $this->load->model('like_model');
        $this->load->library('blog_helper');
    }
 
    //--------------------------------------------------------------------
 
    public function index() 
    {
        $this->load->helper('typography');
 
        Template::set('posts', $this->post_model->order_by('created_on', 'asc')->limit(5)->find_all());
		
        Template::set('viewed', $this->blog_helper->getMostViewed());
        Template::set('liked', $this->blog_helper->getMostLiked());
        
        Template::render('index_without_slider');
    }
 
    //--------------------------------------------------------------------
    
    public function view($id) 
    {
        $this->load->helper('typography');
        
        $post = $this->post_model->find($id);
        
        $this->post_model->update_where('id',$id,array('total_view'=>$post->total_view+1));
        
        Template::set('viewed', $this->blog_helper->getMostViewed());
        Template::set('liked', $this->blog_helper->getMostLiked());
 
        Template::set('post', $post);
 
        Template::render('index_without_slider');
    }
    
    //--------------------------------------------------------------------
    
    public function like($id)
    {
    	$this->load->library('users/auth');
    	
    	$user_id = $this->auth->user_id();
    	$data = array(
    		'user_id'=>$user_id,
    		'blog_id'=>$id	
    	);
    	
    	$like_data = $this->like_model->find_all_by('user_id',$user_id);
    	$flag = 0;
    	if(!empty($like_data))
    	{
	    	foreach ($like_data as $like) 
	    	{
	    		if($like->blog_id == $id)
	    		{
	    			$flag = 1;
	    		}
	    	}
    	}
    	if(!$flag)
    	{
	    	$this->like_model->insert($data);
	    	
	    	$post = $this->post_model->find($id);
        
	        $this->post_model->update_where('id',$id,array('total_like'=>$post->total_like+1));
	        
    	}
    }
 
    //--------------------------------------------------------------------
 
}